<template>
  <view class="IpInput">
    <view class="bottom">
      <view class="bottom-view">
        <div> 发送指令：{{ JSON.stringify(formData) }}</div>
        <div>连接IP信息：{{ resMessage }}</div>
        <view class="view-block-base">
          <el-input class="view-block-input" v-model="ipValue" placeholder="请输入IP及端口" />
        </view>

        <div>
          <el-button class="re-btn" type="primary" @click="init()">重新连接</el-button>
        </div>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { toRefs, watch, ref, onMounted, onUnmounted } from 'vue';
import { WebSocketService } from '@/utils/websocket'


const props = defineProps({
  ipKey: {
    type: String,
    required: true,
    default: ''
  },
  formData: {
    type: Object as any,
    default: {}
  }
})
const { ipKey, formData } = toRefs(props)

let wsService: any = null
const ipValue: any = ref(localStorage.getItem(ipKey.value) || '172.20.4.179:7456') // 172.20.4.179:7456 172.20.4.199:7456
const resMessage = ref('')

const emit = defineEmits(['open', 'getMessage'])

function init() {
  let webSocketurl = `ws://${ipValue.value}`
  wsService?.disconnect()
  wsService = new WebSocketService(webSocketurl)
  if (!wsService?.connect()) return

  wsService.on('message', (data: any) => {
    console.log('接收到消息:', data);
    emit('getMessage', data)
  });
  emit('open', wsService)
}


watch(() => ipValue.value, (val) => {
  localStorage.setItem(ipKey.value, val)
}, {
  // deep: true,
  // immediate: true
})
watch(() => ipKey.value, (val) => {
  init()
})

defineExpose({
  wsService,
})

onMounted(() => {
  init()
})

onUnmounted(() => {
  wsService?.disconnect();
});

</script>
<style lang="scss">
.bottom {
  // position: fixed;
  z-index: 9;
  width: 100%;
  bottom: 0;
  padding: 0 10px;
  box-sizing: border-box;

  .view-block {
    // background: $uni-primary;
    height: 48px;
    line-height: 48px;
    width: 100%;
    // @include baseBlock;
    color: white;
  }

  .view-block-base {
    // background: $uni-base;
    height: 32px;
    line-height: 32px;
    width: 100%;
    // @include baseBlock;

    .view-block-input {
      border: 0px;
      width: 500px !important;
    }
  }

  .re-btn {
    margin-top: 10px;
  }

  .uni-input {
    margin-bottom: 10rpx;
  }
}

input {
  width: 100%;
  border: 1px solid #666;
  height: 26px;
  line-height: 26px;
}
</style>
  